package com.chmingx.boot.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 普通的controller用来转发请求
 */
@Controller
public class RequestController {

    @GetMapping("/goto")
    public String goToPage(HttpServletRequest request) {
        // 为请求设置属性
        request.setAttribute("msg", "成功转发");
        request.setAttribute("code", "200");
        return "forward:/success"; // 转发到 /success 请求
    }

    @ResponseBody
    @GetMapping("/success")
    public Map success(@RequestAttribute("msg") String msg,
                       @RequestAttribute("code") Integer code,
                       HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        // 通过request.getAttribute 获取请求域属性
        map.put("request_method", request.getAttribute("msg"));
        // 利用注解 @RequestAttribute 获取请求域属性
        map.put("annotation", msg);
        return map;
    }

    @GetMapping("/params")
    public String testParams(Map<String, Object> map,
                             Model model,
                             HttpServletRequest request,
                             HttpServletResponse response) {
        map.put("aaa", "aaa");
        model.addAttribute("bbb", "bbb");
        request.setAttribute("ccc", "ccc");

        Cookie cookie = new Cookie("c1", "v1");
        response.addCookie(cookie);
        return "forward:/testparams";
    }

    @ResponseBody
    @GetMapping("/testparams")
    public Map testComplictParams(@RequestAttribute(value = "msg", required = false) String msg,
                                  @RequestAttribute(value = "code", required = false) Integer code,
                                  HttpServletRequest request) {

        Map<String, Object> map = new HashMap<>();
        Object aaa = request.getAttribute("aaa");
        Object bbb = request.getAttribute("bbb");
        Object ccc = request.getAttribute("ccc");

        map.put("aaa", aaa);
        map.put("bbb", bbb);
        map.put("ccc", ccc);

        return map;
    }
}
